package com.qiu.wbpostman.action;

import java.util.List;
import java.util.Map;

import weibo4j.RateLimitStatus;
import weibo4j.Status;
import weibo4j.User;
import weibo4j.Weibo;
import weibo4j.http.AccessToken;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;

public class LoginAction implements Action{
	private User user;
	
	private List<Status> friendsTimeline; //好友的微博
	
	public String execute() throws Exception {
		ActionContext context = ActionContext.getContext();
		Map session = context.getSession();
		AccessToken accessToken = (AccessToken)session.get("accessToken");
		Weibo weibo = null;
		if(session.get("weibo") == null){
			weibo = getWeibo(true,accessToken,"","");
			session.put("weibo", weibo);
		}else {
			weibo = (Weibo)session.get("weibo");
		}
		user = weibo.getUserDetail(accessToken.getUserId()+""); // 得到登录者weibo信息
		// 取得当前微博列表
		friendsTimeline = weibo.getFriendsTimeline();
		
		RateLimitStatus rls = weibo.rateLimitStatus();
		System.out.println("访问频率限制:"+rls.toString());
		if(user.getId()>0) {
			return SUCCESS;
		}
		return null;
	}
	
	private static Weibo getWeibo(boolean isOauth,AccessToken accessToken,String id,String password){
		Weibo weibo = new Weibo();
		if(isOauth) {
			weibo.setToken(accessToken.getToken(), accessToken.getTokenSecret());
		}
		else {
			weibo.setUserId(id);
			weibo.setPassword(password);
		}
		return weibo;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<Status> getFriendsTimeline() {
		return friendsTimeline;
	}

	public void setFriendsTimeline(List<Status> friendsTimeline) {
		this.friendsTimeline = friendsTimeline;
	}
}
